library("shiny")
library("plotly")
library("dtw")
library("tidyr")

source("funkce.R")

ui=fluidPage(
  
  navbarPage("DOS",
             tabPanel("Vizualni",

  titlePanel("Vizualni analyza DOS krivek"),
            sidebarLayout(
              sidebarPanel(
                checkboxGroupInput("SiNi", label = h3("Vyberte"),
                                   choices = list("Si" = "Si", "Ni" = "Ni"),
                                   selected = list("Si", "Ni"))
              ),

              mainPanel(
                plotlyOutput("grafik")
              )
            )
  ),
  
  tabPanel("Korelace Stabilni",
           plotlyOutput("grafkorStabB"), 
           plotlyOutput("vyberStabB")
  ),
  
  tabPanel("Korelace Nestabilni",
           plotlyOutput("grafkorNeStabB"),
           plotlyOutput("vyberNeStabB")
  ),
  tabPanel("DTW Stabilni",
           plotlyOutput("grafDTWmindistSTAB"),
           plotlyOutput("vyberdtw")
  ),
  tabPanel("DTW Nestabilni",
           plotlyOutput("grafDTWmindistNESTAB"),
           plotlyOutput("vyberdtwN")
  ),
  tabPanel("Vzd?lenost Stabilni",
           plotlyOutput("grafDistBodStab"),
           plotlyOutput("vyberDist")
  ),
  tabPanel("Vzd?lenost Nestabilni",
           plotlyOutput("grafDistBodNestab"),
           plotlyOutput("vyberDistN")
  ),
  tabPanel("DOKPHV Stabiln?",
           plotlyOutput("outBarS"),
           plotlyOutput("outPlotS")
  ),
  tabPanel("DOKPHV Nestabiln?",
           plotlyOutput("outBarN"),
           plotlyOutput("outPlotN")
  )
)
)

server = function(input,output){
  val = reactiveValues(
    dfkrych = read.csv("Data/dos-Bulk.csv",header=T, sep=",", dec="."),
    dfstab = read.csv("Data/dos-GB-stable.csv",header=T, sep=",", dec="."),
    dfnestab = read.csv("Data/dos-GB-unstable.csv",header=T, sep=",", dec=".")
  )
  
  output$grafik = renderPlotly({
    if (is.null(input$SiNi)){
      dfkrych = NULL
    } else if (all(input$SiNi == c("Si","Ni"))){
      dfkrych = val$dfkrych
      dfstab = val$dfstab
      dfnestab = val$dfnestab
    } else{
      dfkrych = val$dfkrych[,substr(colnames(val$dfkrych),1,2)==input$SiNi | colnames(val$dfkrych) =="Energy"]
      dfstab = val$dfstab[,substr(colnames(val$dfstab),1,2)==input$SiNi | colnames(val$dfstab) =="Energy"]
      dfnestab = val$dfnestab[,substr(colnames(val$dfnestab),1,2)==input$SiNi | colnames(val$dfnestab) =="Energy"]
    }
    #browser()
    #vykreslen? graf?
    if (is.null(dfkrych)){
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      kp=plot_ly(x = c(1, 2), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
          layout(images = list(source = "http://www.chesssetsworld.com/product_images/uploaded_images/choosing.jpg",
                              xref = "x", yref = "y", x = 1, y = 3, sizex = 2, sizey = 2),
                 xaxis = ax, yaxis = ax)
      
    }else{
      p=list()
      
      p[["krych"]]=plot_ly(x=dfkrych$Energy, y=dfkrych[,2], name = paste("B.",colnames(dfkrych)[2],sep=""), type="scatter", mode = "lines",
                           line = list(width = 1)) %>%
        layout(title = "DOS",
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "DOS bulk"))
      
      if(ncol(dfkrych)>2)
        for (i in 3:ncol(dfkrych))
          p[["krych"]] = add_trace(p[["krych"]], y=dfkrych[,i], name = paste("B.",colnames(dfkrych)[i],sep=""), mode="lines",
                                   line = list(width = 1))
      
      
      p[["stab"]]=plot_ly(x=dfstab$Energy, y=dfstab[,2], name = colnames(dfstab)[2], type="scatter", mode = "lines",
                          legendgroup = 1, showlegend = T, line = list(width = 1)) %>%
        layout(xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "DOS stable"))
      
      for (i in 3:ncol(dfstab))
        p[["stab"]] = add_trace(p[["stab"]], y=dfstab[,i], name = colnames(dfstab)[i], mode="lines",
                                legendgroup = i, showlegend = T, line = list(width = 1))
      
      
      p[["nestab"]]=plot_ly(x=dfnestab$Energy, y=dfnestab[,2], name = colnames(dfnestab)[2], type="scatter", mode = "lines",
                            legendgroup = 1, showlegend = F, line = list(width = 1)) %>%
        layout(xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "DOS unstable"))
      
      for (i in 3:ncol(dfnestab))
        p[["nestab"]] = add_trace(p[["nestab"]], y=dfnestab[,i], name = colnames(dfnestab)[i], mode="lines",
                                  legendgroup = i, showlegend = F, line = list(width = 1))
      
      kp=subplot(p, nrows = 3, titleY = TRUE, shareX = T)
    }
    kp
  })
  
  # stabilni s bulkem
  output$grafkorStabB = renderPlotly({
     # browser()
    df=val$dfstab[,-1]
    kor=cor(val$dfkrych[,2], df[,1])
    
    for (i in 2:ncol(df)){
      if(substr(colnames(df)[i],start = 1,stop = 2)=="Si"){
        k=val$dfkrych[,2]
      } else{
          k=val$dfkrych[,3]
      }
    
      
      kor=c(kor, cor(k, df[,i]))
    }
    
    plot_ly(x = colnames(df),y = kor,type = "bar", source = "bar1")
  })
  
  # nestabilni s bulkem
  output$grafkorNeStabB = renderPlotly({
    # browser()
    df=val$dfnestab[,-1]
    kor=cor(val$dfkrych[,2], df[,1])
    
    for (i in 2:ncol(df)){
      if(substr(colnames(df)[i],start = 1,stop = 2)=="Si"){
        k=val$dfkrych[,2]
      } else{
        k=val$dfkrych[,3]
      }
      
      
      kor=c(kor, cor(k, df[,i]))
    }
    
    plot_ly(x = colnames(df),y = kor,type = "bar", source = "bar2")
  })

  # korelace stabilni s bulk
  output$vyberStabB = renderPlotly({
    s=event_data("plotly_click", source = "bar1")
    #browser()
    if (!is.null(s)){
      p=plot_ly(x=val$dfstab$Energy, y=data.frame(val$dfkrych[,substr(colnames(val$dfkrych),1,2)==substr(s$x,1,2)])[,1], name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("DOS", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "DOS"))

      p = add_trace(p, y=val$dfstab[s$x][,1], name = "stabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)

      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }

    p
  })
  
  # korelace nestabilni s bulk
  output$vyberNeStabB = renderPlotly({
    s=event_data("plotly_click", source = "bar2")
    #browser()
    if (!is.null(s)){
      p=plot_ly(x=val$dfstab$Energy, y=data.frame(val$dfkrych[,substr(colnames(val$dfkrych),1,2)==substr(s$x,1,2)])[,1], name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("DOS", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "DOS"))
      
      p = add_trace(p, y=val$dfnestab[s$x][,1], name = "nestabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }
    
    p
  })
  
  output$grafDTWmindistSTAB = renderPlotly({
    
    df=val$dfstab[,-1]
    e = val$dfstab$Energy
    
    d = NULL
    for (i in 1:ncol(df)){
      if(substr(colnames(df)[i],start = 1,stop = 2)=="Si"){
        d1 = val$dfkrych[,2]
      } else{
        d1 = val$dfkrych[,3]
      }
      
      d = c(d,dtwMinLength(d1, df[,i]))
    }
    
    plot_ly(x = colnames(df), y = d, type = "bar", source = "dtw")
  })
  output$vyberdtw = renderPlotly({
    s=event_data("plotly_click", source = "dtw")
    #browser()
    if (!is.null(s)){
      p=plot_ly(x=val$dfstab$Energy, y=data.frame(val$dfkrych[,substr(colnames(val$dfkrych),1,2)==substr(s$x,1,2)])[,1], name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("DOS", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "DOS"))
      
      p = add_trace(p, y=val$dfstab[s$x][,1], name = "stabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }
    
    p
  })
  
  output$grafDTWmindistNESTAB = renderPlotly({
    
    df=val$dfnestab[,-1]
    e = val$dfnestab$Energy
    
    d = NULL
    for (i in 1:ncol(df)){
      if(substr(colnames(df)[i],start = 1,stop = 2)=="Si"){
        d1 = val$dfkrych[,2]
      } else{
        d1 = val$dfkrych[,3]
      }
      
      d = c(d,dtwMinLength(d1, df[,i]))
    }
    
    plot_ly(x = colnames(df), y = d, type = "bar", source = "dtw")
  })
  output$vyberdtwN = renderPlotly({
    s=event_data("plotly_click", source = "dtw")
    #browser()
    if (!is.null(s)){
      p=plot_ly(x=val$dfnestab$Energy, y=data.frame(val$dfkrych[,substr(colnames(val$dfkrych),1,2)==substr(s$x,1,2)])[,1], name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("DOS", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "DOS"))
      
      p = add_trace(p, y=val$dfnestab[s$x][,1], name = "nestabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }
    
    p
  })
  
  output$grafDistBodStab = renderPlotly({
    #browser()
    df= val$dfstab[,-1]
    e = val$dfstab$Energy
    
    d = NULL
    for (i in 1:ncol(df)){
      if(substr(colnames(df)[i],start = 1,stop = 2)=="Si"){
        d1 = val$dfkrych[,2]
      } else{
        d1 = val$dfkrych[,3]
      }
      
      d = c(d,mean(abs(d1-df[,i])))
    }
    
    plot_ly(x = colnames(df), y = d, type = "bar", source = "dist")
  })
  output$vyberDist = renderPlotly({
    s=event_data("plotly_click", source = "dist")
    #browser()
    if (!is.null(s)){
      p=plot_ly(x=val$dfstab$Energy, y=data.frame(val$dfkrych[,substr(colnames(val$dfkrych),1,2)==substr(s$x,1,2)])[,1], name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("DOS", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "DOS"))
      
      p = add_trace(p, y=val$dfstab[s$x][,1], name = "stabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }
    
    p
  })
  
  output$grafDistBodNestab = renderPlotly({
    #browser()
    df= val$dfnestab[,-1]
    e = val$dfnestab$Energy
    
    d = NULL
    for (i in 1:ncol(df)){
      if(substr(colnames(df)[i],start = 1,stop = 2)=="Si"){
        d1 = val$dfkrych[,2]
      } else{
        d1 = val$dfkrych[,3]
      }
      
      d = c(d,mean(abs(d1-df[,i])))
    }
    
    plot_ly(x = colnames(df), y = d, type = "bar", source = "dist2")
  })
  output$vyberDistN = renderPlotly({
    s=event_data("plotly_click", source = "dist2")
    #browser()
    if (!is.null(s)){
      p=plot_ly(x=val$dfnestab$Energy, y=data.frame(val$dfkrych[,substr(colnames(val$dfkrych),1,2)==substr(s$x,1,2)])[,1], name = "Bulk", type="scatter", mode="lines") %>%
        layout(title = paste("DOS", s$x),
               xaxis = list(title = "Energy (eV)"),
               yaxis = list (title = "DOS"))
      
      p = add_trace(p, y=val$dfnestab[s$x][,1], name = "nestabilni", mode="lines")
    } else {
      ax <- list( title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
      
      p=plot_ly(x = c(1, 3), y = c(1, 3), type = 'scatter', mode = 'markers', opacity = 0)  %>%
        layout(images = list(source = "https://i0.wp.com/respectfulinsolence.com/wp-content/uploads/2015/10/choose-wisely.jpg?w=500&ssl=1",
                             xref = "x", yref = "y", x = 1.22, y = 3, sizex = 2, sizey = 2),
               xaxis = ax, yaxis = ax)
    }
    
    p
  })
  
#outliers Florian
  output$outBarS = renderPlotly(({
    
    f=val$dfstab[,substr(colnames(val$dfstab),1,2)=="Ni"]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid), n=10)
    
    plot_ly(x = out$score[,1], y = out$score[,2], type = "bar")
  }))
  output$outPlotS = renderPlotly({
    
    f=val$dfstab[,substr(colnames(val$dfstab),1,2)=="Ni"]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid), n = 10)

    outliers = out$outliers
    outliers = outliers[outliers != out$less]
    
    outliers_names = substr(outliers, 1, 16)
    #average_name = files()[out()$less]
    
    db = g
    
    data = list()
    for (i in 1:(length(outliers) + 1)) {
      data[[i]] = subset(db, fid == c(outliers, out$less)[i], select = "value")
    }
    
    if (outliers[1] == 0 || length(outliers) == 0) {
      ax <- list(
        title = "",
        zeroline = FALSE,
        showline = FALSE,
        showticklabels = FALSE,
        showgrid = FALSE
      )
      
      if (length(outliers) == 0)
        obr = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcThq1Rnp5TvMhE7O_WMgrjgIJjGE5m_PivAXBlVoCc6EQBIiTK7QA'
      else
        obr = "https://i.imgur.com/0j9LjTZ.png"
      #http://payload247.cargocollective.com/1/14/477282/7242347/tumblr_inline_mmdrnuLP2G1qc4p0k.jpg
      p =
        plot_ly(
          x = c(1, 2, 3),
          y = c(1, 2, 3),
          type = 'scatter',
          mode = 'markers',
          opacity = 0
        ) %>%
        layout(
          images =
            list(
              source = obr,
              #https://upload.wikimedia.org/wikipedia/en/thumb/b/bf/Bosch-brand.svg/1280px-Bosch-brand.svg.png
              #https://i.imgur.com/0j9LjTZ.png
              xref = "x",
              yref = "y",
              x = 1,
              y = 3,
              sizex = 2,
              sizey = 2
            ),
          xaxis = ax,
          yaxis = ax
        )
    } else {
      p <-
        plot_ly(
          x = val$dfstab$Energy,
          y = data[[1]]$value,
          type = 'scatter',
          mode = 'lines',
          name = outliers_names[1],
          opacity = 0.5
        ) %>%
        # Set layout (Title, axis labels, legend, ...)
        layout(legend = list(y = 0.5))
      # Plot other selected curves using add_trace
      
      if (length(outliers_names) > 1) {
        for (i in 2:(length(outliers))) {
          if (outliers[i - 1] != 0)
            p <-
              add_trace(
                p,
                x = val$dfstab$Energy,
                y = data[[i]]$value,
                type = 'scatter',
                mode = 'lines',
                opacity = 0.5,
                name = outliers_names[i]
              )
        }
      }
      p =
        add_trace(
          p,
          x = val$dfstab$Energy,
          y = data[[i + 1]]$value,
          type = 'scatter',
          mode = 'lines',
          opacity = 1,
          name = "Zcela prumerna a nevyrazna",
          line = list(color = rgb(0, 0, 0), width = 3)
        ) 
    }  
    
    return(p)
  })
  
  output$outBarN = renderPlotly(({
    
    f=val$dfnestab[,substr(colnames(val$dfnestab),1,2)=="Ni"]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid), n=10)
    
    plot_ly(x = out$score[,1], y = out$score[,2], type = "bar")
  }))
  output$outPlotN = renderPlotly({
    
    f=val$dfnestab[,substr(colnames(val$dfnestab),1,2)=="Ni"]
    g=gather(f,fid,value)
    
    out = outliers(g,unique(g$fid), n = 10)
    
    outliers = out$outliers
    outliers = outliers[outliers != out$less]
    
    outliers_names = substr(outliers, 1, 16)
    #average_name = files()[out()$less]
    
    db = g
    
    data = list()
    for (i in 1:(length(outliers) + 1)) {
      data[[i]] = subset(db, fid == c(outliers, out$less)[i], select = "value")
    }
    
    if (outliers[1] == 0 || length(outliers) == 0) {
      ax <- list(
        title = "",
        zeroline = FALSE,
        showline = FALSE,
        showticklabels = FALSE,
        showgrid = FALSE
      )
      
      if (length(outliers) == 0)
        obr = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcThq1Rnp5TvMhE7O_WMgrjgIJjGE5m_PivAXBlVoCc6EQBIiTK7QA'
      else
        obr = "https://i.imgur.com/0j9LjTZ.png"
      #http://payload247.cargocollective.com/1/14/477282/7242347/tumblr_inline_mmdrnuLP2G1qc4p0k.jpg
      p =
        plot_ly(
          x = c(1, 2, 3),
          y = c(1, 2, 3),
          type = 'scatter',
          mode = 'markers',
          opacity = 0
        ) %>%
        layout(
          images =
            list(
              source = obr,
              #https://upload.wikimedia.org/wikipedia/en/thumb/b/bf/Bosch-brand.svg/1280px-Bosch-brand.svg.png
              #https://i.imgur.com/0j9LjTZ.png
              xref = "x",
              yref = "y",
              x = 1,
              y = 3,
              sizex = 2,
              sizey = 2
            ),
          xaxis = ax,
          yaxis = ax
        )
    } else {
      p <-
        plot_ly(
          x = val$dfnestab$Energy,
          y = data[[1]]$value,
          type = 'scatter',
          mode = 'lines',
          name = outliers_names[1],
          opacity = 0.5
        ) %>%
        # Set layout (Title, axis labels, legend, ...)
        layout(legend = list(y = 0.5))
      # Plot other selected curves using add_trace
      
      if (length(outliers_names) > 1) {
        for (i in 2:(length(outliers))) {
          if (outliers[i - 1] != 0)
            p <-
              add_trace(
                p,
                x = val$dfnestab$Energy,
                y = data[[i]]$value,
                type = 'scatter',
                mode = 'lines',
                opacity = 0.5,
                name = outliers_names[i]
              )
        }
      }
      p =
        add_trace(
          p,
          x = val$dfnestab$Energy,
          y = data[[i + 1]]$value,
          type = 'scatter',
          mode = 'lines',
          opacity = 1,
          name = "Zcela prumerna a nevyrazna",
          line = list(color = rgb(0, 0, 0), width = 3)
        ) 
    }  
    
    return(p)
  })
}

shinyApp(ui = ui, server = server)

